<?php
declare (strict_types = 1);
namespace app\common;

use think\db\Query;
use think\Paginator;

class QueryExt extends Query
{
    public function getInfo($where)
    {
        if (!is_array($where)) {
            $where = ['id' => (int) $where];
        }
        return $this->where($where)->find();
    }

    public function getList($where = null)
    {
        if (!empty($where)) {
            $this->where($where);
        }
        return $this->select();
    }

    public function saveInfo($data, $where)
    {
        if (!is_array($where)) {
            $where = ['id' => (int) $where];
        }
        return $this->where($where)->save($data) === false ? false : true;
    }

    public function setInfo($data, $key, $update = false)
    {
        $where = [];
        foreach (explode(',', $key) as $k) {
            $where[$k] = $data[$k];
        }
        $field = array_keys($data);
        $field[] = 'id';
        $info = $this->field($field)->where($where)->find();
        if (empty($info)) {
            return $this->newQuery()->insertGetId($data);
        } else {
            $data['id'] = $info['id'];
            if ($update && !empty(array_diff_assoc($data, $info))) {
                $this->newQuery()->update($data);
            }
            return $info['id'];
        }
    }

    public function getPage($page, $size = 10): Paginator
    {
        return $this->paginate([
            'page' => $page,
            'list_rows' => $size,
        ]);
    }
}
